//
//  ClubForumDetailTableViewCell.swift
//  77Club
//
//  Created by Apple on 2024/9/6.
//

import UIKit
import WebKit

class ClubForumDetailTableViewCell: UITableViewCell {
    
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(17.font_semiBold).line(0).end()
//    private let userView = c_make_ex(UIView.self)
//        .bgColor("#EDEEF0").corner(12.0.Scale).end()
//    private let userImageView = c_make_ex(UIImageView.self)
//        .corner(18.0.Scale).mode(.scaleAspectFill).end()
//    private let nameLabel = c_make_ex(UILabel.self)
//        .color(.black).font(13.font_medium).end()
//    private let timeLabel = c_make_ex(UILabel.self)
//        .color("#808080").font(11.font_medium).end()
    private let contentWebView = WKWebView()
    private let commitLabel = c_make_ex(UILabel.self)
        .color(.black).font(13.font_semiBold)
        .text("全部评论").end()
    private let sortButton = c_make_ex(UIButton.self)
        .image("GameDetail_sortNor").image("GameDetail_sortSel", state: .selected).end()
    
    var updateDataBlock: ((_ model: ClubGameCommunityDetailModel) -> Void)?
    var sortByDataBlock: ((_: String) -> Void)?
    
    var sortBy: String = "0"{
        didSet{
            self.sortButton.isSelected = sortBy == "0"
        }
    }
    var model: ClubGameCommunityDetailModel?{
        didSet{
            guard let md = model else { return }
            
            if md.webViewH > 0 {
                contentWebView.heightConstraint?.constant = md.webViewH
            }
            titleLabel.text = md.title
//            userImageView.loadImage(url: md.face)
//            nameLabel.text = md.fabu
//            timeLabel.text = md.time
            // 将 Base64 字符串解码为 Data
            guard let decodedData = Data(base64Encoded: md.content)else { return }
            // 将 Data 转换为字符串
            let decodedString = String(data: decodedData, encoding: .utf8)
            self.loadHTML(htmlString: decodedString ?? "")
        }
    }
    
    var commitModel: [ClubGameCommunityDetailCommentModel]? {
        didSet{
            guard let md = commitModel else { return }
            
            if md.count > 0 {
                commitLabel.isHidden = false
                sortButton.isHidden = false
                commitLabel.heightConstraint?.constant = 15.0.Scale
            }else{
                commitLabel.isHidden = true
                sortButton.isHidden = true
                commitLabel.heightConstraint?.constant = 0
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            titleLabel
//            userView.subviews{
//                userImageView
//                nameLabel
//                timeLabel
//            }
            contentWebView
            commitLabel
            sortButton
        }
        
        titleLabel.leading(12.0.Scale).trailing(12.0.Scale).top(12.0.Scale)
//        userView.leading(12.0.Scale).trailing(12.0.Scale).height(55.0.Scale)
//        userView.Top == titleLabel.Bottom + 20.0.Scale
//        userImageView.leading(16.0.Scale).size(36.0.Scale).centerVertically()
//        nameLabel.leading(62.0.Scale).trailing(90.0.Scale)
//        nameLabel.Top == userImageView.Top
//        timeLabel.leading(62.0.Scale).trailing(90.0.Scale)
//        timeLabel.Top == nameLabel.Bottom + 1.0.Scale
        contentWebView.leading(12.0.Scale).trailing(12.0.Scale).height(35)
        contentWebView.Top == titleLabel.Bottom + 20.0.Scale
        commitLabel.leading(12.0.Scale).bottom(16.0.Scale).height(15.0.Scale)
        commitLabel.Top == contentWebView.Bottom + 30
        sortButton.trailing(12.0.Scale).width(76.0.Scale).height(28.0.Scale)
        sortButton.CenterY == commitLabel.CenterY
        
        contentWebView.navigationDelegate = self
        contentWebView.backgroundColor = .clear
        contentWebView.isUserInteractionEnabled = true
        
        contentWebView.scrollView.isScrollEnabled = false // 禁用滚动
        contentWebView.scrollView.bounces = false // 禁用边界回弹
        
        sortButton.addTarget(self, action: #selector(clickSortButton), for: .touchUpInside)
    }

    @objc private func clickSortButton(){
        
        sortButton.isSelected = !sortButton.isSelected
        let sortType = sortButton.isSelected ? "0" : "1"
        sortByDataBlock?(sortType)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

extension ClubForumDetailTableViewCell: WKNavigationDelegate {
    
    private func loadHTML(htmlString: String) {
        let resultString = htmlString
            .replacingOccurrences(of: "\"", with: "")
        // 补全 HTML 结构
        let completeHTMLString = """
                    <html>
                    <head>
                        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
                        <style>
                            body { font-family: -apple-system, Arial; font-size: 16px; margin: 0; padding: 0; }
                            iframe { max-width: 100%; height: auto; }
                            img {
                                max-width: 100%;
                                height: auto;
                            }
                        </style>
                    </head>
                    <body>
                        \(resultString)
                    </body>
                    </html>
                    """
                    
                    // 加载 HTML
        contentWebView.loadHTMLString(completeHTMLString, baseURL: nil)
    }
    
    // 当页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 执行 JavaScript 来计算内容的高度
        if let h = model?.webViewH, h > 0 {} else{
            webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] result, error in
                if let height = result as? CGFloat {
                    // 更新 WebView 高度
                    self?.model?.webViewH = height
                    if let md = self?.model {
                        self?.updateDataBlock?(md)
                    }
                }
            }
        }
    }
    
    // 拦截超链接点击事件
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            
        if let url = navigationAction.request.url {
            if navigationAction.navigationType == .linkActivated {
                print("用户点击了链接：\(url.absoluteString)")
                    
                // 根据需要处理点击事件
                if url.absoluteString.contains("pan.quark.cn") {
                    print("拦截到夸克链接")
                    UIPasteboard.general.string = url.absoluteString
                    ClubGlobalTool.shared.openQuarkNetdisk(urlString: url.absoluteString)
                } else if url.absoluteString.contains("pan.baidu.com") {
                    print("拦截到百度链接")
                    UIPasteboard.general.string = url.absoluteString
                    ClubGlobalTool.shared.openBaiduNetdisk(urlString: url.absoluteString)
                } else if url.absoluteString.contains("alipan.com") {
                    print("拦截到阿里链接")
                    UIPasteboard.general.string = url.absoluteString
                    ClubGlobalTool.shared.openAliyunDrive(urlString: url.absoluteString)
                } else {
                    print("未知链接")
                }
                    
                // 如果想要阻止 WebView 跳转，使用 .cancel
                decisionHandler(.cancel)
                return
            }
        }
        
        // 默认允许导航
        decisionHandler(.allow)
    }
}


class ClubForumDetailCommitView: UIView, UITextViewDelegate {

    private let sendButton = c_make_ex(UIButton.self)
        .image("Square_sendDisable").image("Square_send",state: .selected).end()
    lazy var commitView: Custom_TextView = {
        let view = Custom_TextView()
        view.backgroundColor = "#000000".toColor.alpha(0.05)
        view.textContainerInset = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 15)
        view.tintColor = .black
        view.textColor = .black
        view.placeHolderColor = "#7B7D80".toColor
        view.placeHolder = "写点什么..."
        view.placeholderFont = 11.font_medium
        view.returnKeyType = .done
        view.font = 11.font_medium
        view.layer.cornerRadius = 16
        view.layer.masksToBounds = true
        return view
    }()
    var sendTextBlock: ((_ text: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white.alpha(0.8)
        
        subviews{
            commitView
            sendButton
        }

        commitView.delegate = self
        commitView.leading(12.0.Scale).height(32.0.Scale).trailing(65.0.Scale).top(12.0.Scale)
        sendButton.trailing(12.0.Scale).height(32.0.Scale).width(45.0.Scale).top(8.0.Scale)
        
        sendButton.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
    }
    
    @objc private func sendMessage(){
        guard let text = commitView.text, text.count > 0 else { return }
        sendTextBlock?(text)
    }

    // UITextViewDelegate 方法
    func textViewDidChange(_ textView: UITextView) {
        // 获取当前字符数
        let characterCount = textView.text.count
        sendButton.isSelected = characterCount > 0
        // 可在此处添加其他逻辑，例如限制字符长度
        if characterCount > 200 {
            textView.text = String(textView.text.prefix(200))
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
